<!---
Copyright (c) 2007 Brian Billman

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
--->
<cfcomponent displayname="CFSmugBase" output="false" hint="Do not instantiate this CFC directly">

	<cffunction name="init" access="public" output="false" returntype="CFSmugBase">
		<cfargument name="config" type="CFSmugConfig" required="true" hint="CFC instance that contains configuration information" />

		<cfset Variables.properties = StructNew() />

		<cfset setConstants() />
		<cfset setConfig( Arguments.config ) />

		<cfreturn this />
	</cffunction>

	<cffunction name="setConstants" access="private" output="false" returntype="void">
		<cfscript>
			Variables.properties.constants.API_VERSION = "1.2.0";

			Variables.properties.constants.SERVICE_URL_1_2_0_REST = "api.smugmug.com/hack/rest/1.2.0/";
			Variables.properties.constants.SERVICE_URL_1_2_1_REST = "api.smugmug.com/services/api/rest/1.2.1/";
			Variables.properties.constants.SERVICE_URL_UPLOAD_HTTP_PUT = "http://upload.smugmug.com/";

			Variables.properties.constants.RESPONSE_TYPE = "REST";

			Variables.properties.constants.errors = StructNew();
			Variables.properties.constants.errors.INVALID_LOGIN = 1;
			Variables.properties.constants.errors.INVALID_SESSION = 3;
			Variables.properties.constants.errors.INVALID_USER = 4;
			Variables.properties.constants.errors.INVALID_SORT_METHOD = 12;
			Variables.properties.constants.errors.INVALID_SORT_DIRECTION = 13;
			Variables.properties.constants.errors.EMPTY_SET = 15;
			Variables.properties.constants.errors.INVALID_METHOD = 17;
			Variables.properties.constants.errors.INVALID_API_KEY = 18;
		</cfscript>
	</cffunction>

	<cffunction name="getConfig" access="public" output="false" returntype="CFSmugConfig">
		<cfreturn Variables.properties.config />
	</cffunction>

	<cffunction name="setConfig" access="public" output="false" returntype="void">
		<cfargument name="config" type="CFSmugConfig" required="true" />
		<cfset Variables.properties.config = Arguments.config />
	</cffunction>

	<cffunction name="getAPIVersion" access="public" output="false" returntype="string">
		<cfreturn Variables.properties.constants.API_VERSION />
	</cffunction>

	<cffunction name="getStandardServiceURL" access="private" output="false" returntype="string">
		<cfreturn "http://" & Variables.properties.constants.SERVICE_URL_1_2_0_REST />
	</cffunction>

	<cffunction name="getSecureServiceURL" access="private" output="false" returntype="string">
		<cfreturn "https://" & Variables.properties.constants.SERVICE_URL_1_2_0_REST />
	</cffunction>

	<cffunction name="getUploadServiceURL" access="private" output="false" returntype="string">
		<cfreturn Variables.properties.constants.SERVICE_URL_UPLOAD_HTTP_PUT />
	</cffunction>

	<cffunction name="getResponseType" access="private" output="false" returntype="string">
		<cfreturn Variables.properties.constants.RESPONSE_TYPE />
	</cffunction>

	<cffunction name="getErrorCodes" access="public" output="false" returntype="struct">
		<cfreturn Variables.properties.constants.errors />
	</cffunction>

	<cffunction name="doRemoteInvocation" access="private" output="false" returntype="xml">
		<cfargument name="method" type="string" required="true" />
		<cfargument name="args" type="struct" required="false" />
		<cfargument name="secureMode" type="boolean" required="false" default="false" />
		<cfargument name="upload" type="boolean" required="false" default="false" hint="True if uploading an image to smugmug" />

		<cfset var httpMethod = 0 />
		<cfset var paramType = 0 />
		<cfset var httpResult = 0 />
		<cfset var serviceUrl = 0 />
		<cfset var timeout = 0 />
		<cfset var currentArg = 0 />
		<cfset var logText = 0 />

		<cfif Arguments.upload>
			<cfset httpMethod = "put" />
			<cfset paramType = "header" />
			<cfset timeout = getConfig().getSmugMugUploadTimeout() />
			<cfset serviceUrl = getUploadServiceURL() & Arguments.args["X-Smug-FileName"] />
		<cfelse>
			<cfset httpMethod = "get" />
			<cfset paramType = "url" />
			<cfset timeout = getConfig().getSmugMugRequestTimeout() />

			<cfif Arguments.secureMode Or getConfig().isPreferSecureMode()>
				<cfset serviceUrl = getSecureServiceURL() />
			<cfelse>
				<cfset serviceUrl = getStandardServiceURL() />
			</cfif>
		</cfif>

		<cftry>
			<cfif getConfig().isDebugEnabled()>
				<cfset logText = createObject( "java", "java.lang.StringBuffer" ).init() />
				<cfset logText.append( "httpMethod=[#httpMethod#],paramType=[#paramType#],timeout=[#timeout#]," ) />
				<cfset logText.append( "serviceUrl=[#serviceUrl#],userAgent=[#getConfig().getUserAgent()#]" ) />

				<cfif Not Arguments.upload>
					<cfset logText.append( ",method=[#Arguments.method#],APIKey=[#getConfig().GetAPIKey()#]" ) />
				</cfif>

				<cfif structKeyExists( Arguments, "args" ) And Not StructIsEmpty( Arguments.args )>
					<cfloop collection="#Arguments.args#" item="currentArg">
						<cfif UCase( currentArg ) neq "DATA">
							<cfset logText.append( ",#currentArg#=[#Arguments.args[currentArg]#]" ) />
						</cfif>
					</cfloop>
				</cfif>
				<cfif Arguments.upload>
					<cfset logText.append( ",http request body=[#Len( Arguments.args["Data"] )# bytes of binary data ]" ) />
				</cfif>

				<cfset logAction( file="CFSmug.CFSmugBase.doRemoteInvocation", text="HTTP Request Info={#logText.toString()#}" ) />
			</cfif>


			<!--- Note that REST URL arguments ARE case sensitive! --->
			<cfhttp method="#httpMethod#"
					redirect="false"
					charset="utf-8"
					result="httpResult"
					useragent="#getConfig().getUserAgent()#"
					timeout="#timeout#"
					throwonerror="true"
					url="#serviceUrl#">

				<cfif Not Arguments.upload>
					<cfhttpparam type="#paramType#" name="method" value="#Arguments.method#" />
					<cfhttpparam type="#paramType#" name="APIKey" value="#getConfig().GetAPIKey()#" />
				</cfif>

				<cfif structKeyExists( Arguments, "args" ) And Not StructIsEmpty( Arguments.args )>
					<cfloop collection="#Arguments.args#" item="currentArg">
						<cfif UCase( currentArg ) neq "DATA">
							<cfhttpparam type="#paramType#" name="#currentArg#" value="#Arguments.args[currentArg]#" />
						</cfif>
					</cfloop>
				</cfif>

				<cfif Arguments.upload>
					<cfhttpparam type="body" value="#Arguments.args["Data"]#" />
				</cfif>
			</cfhttp>

			<cfif Not isXml( httpResult.fileContent )>
				<cfset logAction( file="CFSmug.InvalidResponse", text="Invalid Response Returned (not XML). HTTP Response = [#httpResult.fileContent#]", type="Error" ) />
				<cfthrow type="CFSmug.InvalidResponse" message="Invalid Response Returned (not XML)" extendedinfo="#Left( httpResult.fileContent, 200 )#" />
			</cfif>

			<cfif getConfig().isDebugEnabled()>
				<cfset logAction( file="CFSmug.CFSmugBase.doRemoteInvocation", text="HTTP Response=[#httpResult.fileContent#]" ) />
			</cfif>

			<cfreturn xmlParse( httpResult.fileContent ) />

		<cfcatch type="CFSmug">
			<cfrethrow />
		</cfcatch>
		<cfcatch type="any">
			<cfset logAction( file="CFSmug.CFSmugBase.doRemoteInvocation", text="Message = #cfcatch.message#; Detail = #cfcatch.detail#; StackTrace = #cfcatch.stacktrace#", type="Error" ) />
			<cfrethrow />
		</cfcatch>
		</cftry>
	</cffunction>

	<cffunction name="validateRESTResponse" access="private" output="false" returntype="boolean">
		<cfargument name="responseXML" type="xml" required="true" />
		<cfset var status = 0 />

		<cfif isDefined( "Arguments.responseXML.rsp.XmlAttributes.stat" )>
			<cfset status = LCase( Arguments.responseXML.rsp.XmlAttributes.stat ) />
		<cfelse>
			<!--- malformed response --->
			<cfset logAction( file="CFSmug.InvalidResponse", text="Message = Invalid response received; Detail = XML not in expected format; Response=[#Arguments.responseXML#]", type="Error" ) />
			<cfthrow type="CFSmug.InvalidResponse" message="Invalid response received" detail="XML not in expected format.  Response=[#Arguments.responseXML#]" />
		</cfif>

		<cfif status eq "ok">
			<cfreturn true />
		<cfelseif status eq "fail">
			<cfif isDefined( "Arguments.responseXML.rsp.err.XmlAttributes.code" ) and
			  	  isDefined( "Arguments.responseXML.rsp.err.XmlAttributes.msg" )>
				<!--- known error condition, rethrow --->
				<!--- TODO: throw a different type of error for known smugmug error codes --->
				<cfset logAction( file="CFSmug.SmugMugException", text="Error Code = #Arguments.responseXML.rsp.err.XmlAttributes.code#. Message = #Arguments.responseXML.rsp.err.XmlAttributes.msg#", type="Information" ) />
				<cfthrow type="CFSmug.SmugMugException" errorcode="#Arguments.responseXML.rsp.err.XmlAttributes.code#"
						 message="#Arguments.responseXML.rsp.err.XmlAttributes.msg#" />
			<cfelse>
				<!--- known error condition, don't know error, rethrow --->
				<!--- TODO: throw a different error type for unknown smugmug error --->
				<cfset logAction( file="CFSmug.InvalidResponse", text="Message = Failure, no error code or message from SmugMug", type="Warning" ) />
				<cfthrow type="CFSmug.InvalidResponse" message="Failure" detail="Failure, no error code or message from SmugMug" />
			</cfif>
		<cfelse>
			<!--- unknown status --->
			<cfset logAction( file="CFSmug.InvalidResponse", text="Message = Unknown status received; Status = '#status#'", type="Warning" ) />
			<cfthrow type="CFSmug.InvalidResponse" message="Unknown status received" detail="status = '#status#'" />
		</cfif>

	</cffunction>

	<cffunction name="createAlbumStruct" access="private" output="false" returntype="struct">
		<cfargument name="AlbumNode" type="xml" required="true" />

		<cfset var x = Arguments.AlbumNode />
		<cfset var s = StructNew() />

		<cfscript>
			if ( StructKeyExists( x, "XmlAttributes" ) )
			{
				StructAppend( s, x.XmlAttributes );
				renameKey( s, "AlbumID" );
			}

			// non-attributes
			if ( StructKeyExists( x, "Category" ) )
			{
				s["Category"] = StructNew();
				s["Category"] = createCategoryStruct( x.Category );
			}
			if ( StructKeyExists( x, "SubCategory" ) )
			{
				s["SubCategory"] = StructNew();
				s["SubCategory"] = createSubCategoryStruct( x.SubCategory );
			}

			if ( StructKeyExists( x, "Highlight" ) )
			{
				s["Highlight"] = StructNew();
				if ( StructKeyExists( x.Highlight, "XmlAttributes" ) And
					 Not StructIsEmpty( x.Highlight.XmlAttributes ) )
				{
					StructAppend( s["Highlight"], x.Highlight.XmlAttributes );
					renameKey( s["Highlight"], "ImageID" );
				}
			}
			if ( StructKeyExists( x, "Community" ) )
			{
				s["Community"] = StructNew();
				if ( StructKeyExists( x.Community, "XmlAttributes" ) And
					 Not StructIsEmpty( x.Community.XmlAttributes ) )
				{
					StructAppend( s["Community"], x.Community.XmlAttributes );
					renameKey( s["Community"], "CommunityID" );
				}
			}
		</cfscript>

		<cfreturn s />
	</cffunction>

	<cffunction name="createStatsStruct" access="private" output="false" returntype="struct">
		<cfargument name="StatsNode" type="xml" required="true" />
		<cfargument name="ForAlbum" type="boolean" required="false" default="true" />

		<cfset var x = Arguments.StatsNode />
		<cfset var s = StructNew() />
		<cfset var idName = "AlbumID" />

		<cfif Not Arguments.ForAlbum>
			<cfset idName = "ImageID" />
		</cfif>

		<cfscript>
			if ( StructKeyExists( x, "XmlAttributes" ) )
			{
				StructAppend( s, x.XmlAttributes );
				renameKey( s, idName );
			}
		</cfscript>

		<cfreturn s />

	</cffunction>

	<cffunction name="createCategoryStruct" access="private" output="false" returntype="struct">
		<cfargument name="CategoryNode" type="xml" required="true" />

		<cfset var x = Arguments.CategoryNode />
		<cfset var s = StructNew() />

		<cfscript>
			if ( StructKeyExists( x, "XmlAttributes" ) )
			{
				StructAppend( s, x.XmlAttributes );
				renameKey( s, "CategoryID" );
				renameKey( s, "CategoryName", "Name" );
			}
		</cfscript>

		<cfreturn s />
	</cffunction>

	<cffunction name="createSubCategoryStruct" access="private" output="false" returntype="struct">
		<cfargument name="SubCategoryNode" type="xml" required="true" />

		<cfset var x = Arguments.SubCategoryNode />
		<cfset var s = StructNew() />

		<cfscript>
			if ( StructKeyExists( x, "XmlAttributes" ) )
			{
				StructAppend( s, x.XmlAttributes );
				renameKey( s, "SubCategoryID" );
				renameKey( s, "SubCategoryName", "Name" );
			}
			if ( StructKeyExists( x, "Category" ) )
			{
				s["Category"] = StructNew();
				s["Category"] = createCategoryStruct( x.Category );
			}
		</cfscript>

		<cfreturn s />
	</cffunction>

	<cffunction name="createImageStruct" access="private" output="false" returntype="struct">
		<cfargument name="ImageNode" type="xml" required="true" />

		<cfset var x = Arguments.ImageNode />
		<cfset var s = StructNew() />

		<cfscript>
			if ( StructKeyExists( x, "XmlAttributes" ) )
			{
				StructAppend( s, x.XmlAttributes );
				renameKey( s, "ImageID" );
			}

			// non-attributes
			if ( StructKeyExists( x, "Album" ) )
			{
				s["Album"] = StructNew();
				if ( StructKeyExists( x.Album, "XmlAttributes" ) And
					 Not StructIsEmpty( x.Album.XmlAttributes ) )
				{
					StructAppend( s["Album"], x.Album.XmlAttributes );
					renameKey( s["Album"], "AlbumID" );
				}
			}
		</cfscript>

		<cfreturn s />
	</cffunction>

	<cffunction name="renameKey" access="private" output="false" returntype="void">
		<cfargument name="struct" type="struct" required="true" />
		<cfargument name="newKeyName" type="string" required="true" />
		<cfargument name="oldKeyName" type="string" required="false" default="id" />

		<cftry>

			<cfif StructKeyExists( Arguments.struct, Arguments.oldKeyName )>
				<cfset Arguments.struct[Arguments.newKeyName] = Arguments.struct[Arguments.oldKeyName] />
				<cfset StructDelete( Arguments.struct, Arguments.oldKeyName ) />
			</cfif>

			<cfreturn />

			<cfcatch type="any">
				<cfset logAction( file="CFSmug.CFSmugBase.renameKey", text="Invalid Key Name.  Message = #cfcatch.message#; Detail = #cfcatch.detail#; StackTrace = #cfcatch.stacktrace#", type="Error" ) />
				<cfthrow type="CFSmug.CFSmugBase.renameKey" message="Invalid Key Name" detail="#cfcatch.message# #cfcatch.detail#" />
			</cfcatch>
		</cftry>
	</cffunction>

	<cffunction name="createSmugMugArgs" access="private" output="false" returntype="struct">
		<cfargument name="functionMetadata" type="struct" required="true" />
		<cfargument name="argsPassed" type="struct" required="true" />

		<cfset var argNamesArray = Arguments.functionMetadata.parameters />
		<cfset var i = 0 />
		<cfset var currentArg = 0 />
		<cfset var result = StructNew() />

		<cfloop from="1" to="#ArrayLen( argNamesArray )#" index="i">
			<cfif StructKeyExists( Arguments.argsPassed, argNamesArray[i].Name )>
				<cfif Not CompareNoCase( argNamesArray[i].type, "boolean" )>
					<cfif Arguments.argsPassed[argNamesArray[i].Name]>
						<cfset result[argNamesArray[i].Name] = 1 />
					<cfelse>
						<cfset result[argNamesArray[i].Name] = 0 />
					</cfif>
				<cfelse>
					<cfset result[argNamesArray[i].Name] = Arguments.argsPassed[argNamesArray[i].Name] />
				</cfif>
			</cfif>
		</cfloop>

		<cfreturn result />

	</cffunction>


	<cffunction name="logAction" access="private" output="false" returntype="void">
		<cfargument name="File" type="string" required="true" />
		<cfargument name="Text" type="string" required="true" />
		<cfargument name="Type" type="string" required="false" default="Information" hint="Should be one of these 4 values: Information, Warning, Error, Fatal" />

		<cflog file="#getConfig().getDebugLogFileName()#"
			   application="true"
			   type="#UCase( Trim( Arguments.Type ) )#"
			   text="#Trim( Arguments.File )# ~~~ #Trim( Arguments.Text )#" />

		<cfreturn />
	</cffunction>

	<cffunction name="getProperties" access="public" output="false" returntype="struct">
		<cfif structKeyExists( Variables, "properties" )>
			<cfreturn Variables.properties />
		<cfelse>
			<cfreturn structNew() />
		</cfif>
	</cffunction>

</cfcomponent>